package org.ltwitter.gui;

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import winterwell.jtwitter.*;

//Login window
public class LoginWindow {

   //the login window	
	private JFrame loginFrame;
	private JPanel mainPanel,buttonPanel,mainWrapper;
	private JTextField txtUser;
	private JPasswordField txtPassword;
	private JLabel lblUser,lblPassword,lblHead;
	private JButton btSubmit;
	private Icon img;
	
	
	//the login constructor
	public LoginWindow(){
		loginFrame = new JFrame("Twitter Sign In");
		mainPanel = new JPanel();
		mainWrapper = new JPanel();
		buttonPanel = new JPanel();
		txtUser = new JTextField(25);
		txtPassword = new JPasswordField(25);
		lblUser = new JLabel("Twitter Username");
		lblPassword = new JLabel("Password");
		btSubmit = new JButton("Sign In");
		
		img = new ImageIcon("images/LTwitter2.jpg");
		lblHead = new JLabel(img);
		
		txtPassword.setEchoChar('*');
	}
	
	public void show(){
		
		mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.PAGE_AXIS	));
		mainPanel.add(lblUser);
		mainPanel.add(txtUser);
		mainPanel.add(lblPassword);
		mainPanel.add(txtPassword);
		
		mainWrapper.setLayout(new FlowLayout());
		mainWrapper.add(mainPanel);
		
		
		btSubmit.addActionListener(new LoginListener());
		buttonPanel.setLayout(new FlowLayout());
		buttonPanel.add(btSubmit);
//		buttonPanel.add(btClose);
		
		loginFrame.setSize(250,200);
		loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		loginFrame.getContentPane().add(BorderLayout.PAGE_START,lblHead);
		loginFrame.getContentPane().add(BorderLayout.CENTER,mainWrapper);
		loginFrame.getContentPane().add(BorderLayout.PAGE_END,buttonPanel);
		loginFrame.setVisible(true);
		
//		Graphics2D g = new Graphics();
//		g.setColor(Color.WHITE);
//		loginFrame.paint(g);
		
	}
	
	class LoginListener implements ActionListener{
		public void actionPerformed(ActionEvent ev){
			String username = txtUser.getText();
			char[] cpassword = txtPassword.getPassword();
			
			StringBuilder password = new StringBuilder(cpassword.length);
			for(int i=0;i<cpassword.length;i++){
				password.append(cpassword[i]);
			}
			Twitter twtUser = new Twitter(username,password.toString());
			if(twtUser.isValidLogin()){
				Client theclient = new Client();
				theclient.setTwtuser(twtUser);
				theclient.showForm();
//				loginFrame.setVisible(false);
			}
			else{
				JOptionPane.showMessageDialog(null, "Either username or password is wrong");
			}
			txtUser.setText("");
			txtPassword.setText("");	
			//security clearing of the password
			for(int i=0;i<cpassword.length;i++){
				cpassword[i]=' ';
			}
		}
	}
	
	
}
